const { Controller } = require('egg');
const axios = require('axios');

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }

  /**
   * 网关只做权限校验
   */
  async redirect() {
    const ctx = this.ctx;
    let result,
      historyConfig;
    try {

      const config = await ctx.service.home.readyConfig(ctx);
      historyConfig = await ctx.service.home.historyConfig(ctx);
      result = await this.send(config);

      console.log(result)

      ctx.status = result.data.code;
      ctx.body = result.data;

      historyConfig.data.result = result.data;

      if (result.headers) {
        for (const key in result.headers) {
          ctx.set(key, result.headers[key]);
        }
      }

      
      historyConfig.data.type = result.data.code === 200 ? 1 : 2;
      // this.send(historyConfig);
      return;
    } catch (error) {

      historyConfig.data.type = 2;
      // this.send(historyConfig);
      ctx.status = 500;
      ctx.body = {
        code: 500,
        msg: error.message,
      };
      return;
    }
  }


  // 发送请求
  async send(config) {
    try {


      const data = await axios(config);


      return data;

    } catch (error) {

      // console.log(error);
      throw error;
    }
  }
}

module.exports = HomeController;
